package com.framework.foundation.weixin.wxuser;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.framework.foundation.common.BaseService;
import com.framework.foundation.common.vo.IResult;
import com.framework.foundation.common.vo.Result;
import com.framework.foundation.util.HttpServletKit;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.activerecord.tx.Tx;

public class WxuserService extends BaseService<Wxuser> {

	public static final WxuserService me = Enhancer.enhance(WxuserService.class);

	/**
	 * 新增方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	@Before(Tx.class)
	public IResult<Object> save(Wxuser model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			Boolean result = model.save();

			if (result) {
				// 生成授权url和token
				HttpServletRequest request = HttpServletKit.getRequest();
				StringBuffer url = new StringBuffer("http://mobile.hmjxt.com/weixin/?id=" + model.getInt("id"));

				model.set("url", url.toString());
				model.set("token", UUID.randomUUID().toString().replaceAll("-", ""));
				result = model.update();
			}

			return Result.create(result, model);
		} catch (Exception e) {
			throw new RuntimeException("新增异常！", e);
		}
	}

	/**
	 * 编辑方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	public IResult<Object> update(Wxuser model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			model.set("enabled", 0);
			return Result.create(model.update(), model);
		} catch (Exception e) {
			throw new RuntimeException("编辑异常！", e);
		}
	}
}
